 <template>
  <view class="main" >
    <view v-if="isLogin">
    <view class="top">
      <view class="point-box">
        <view class="point-total">{{ userPointCount }}</view>
        <view class="point-btns">
          <view>我的积分</view>
          <view>|</view>
          <view @click="handleToDetail">积分明细<text class="iconfont icon-more1"></text></view>
        </view> 
      </view>

    </view>
    <view class="header">
      <view class="search">
        <view class="search-box">
          <image class="search-icon" src="@/static/svg/icon_search.svg" />
          <input class="search-input" confirm-type="search" v-model="queryData.keyword" @confirm="productReload()" placeholder="搜索商品名称/编码/条码" />
        </view>
      </view>
      <view class="filter">
        <view class="filter-box">
          <view 
            class="filter-type-item filter-classify" 
            :class="{
              'active': groupTagCur,
              'open': showFilterDialog && dialogType === dialogEunm.TAG_GROUPS
              }" 
            @click="handleOpenFilter(dialogEunm.TAG_GROUPS)"
          >
            <view class="filter-name">{{ groupTagCur?.tagName || '全部分类' }}</view>
            <view class="iconfont icon-tag-more"></view>
          </view>
          <view 
            class="filter-type-item filter-classify" 
            :class="{
              'active': groupTagChildCur,
              'open': showFilterDialog && dialogType === dialogEunm.TAG_ITEMS
            }" 
            v-if="groupTagCur" 
            @click="handleOpenFilter(dialogEunm.TAG_ITEMS)"
            >
             <view class="filter-name">{{groupTagChildTitle}}</view>
              <view class="iconfont icon-tag-more"></view>
          </view>
          <view 
            class="filter-type-item filter-sort" 
            :class="{
              'active': queryData.sortType,
              'open': showFilterDialog && dialogType === dialogEunm.SORT
            }" 
            @click="handleOpenFilter(dialogEunm.SORT)"
            >
            <view class="filter-name">{{getSortTitle}} </view>
            <view class="iconfont icon-tag-more" ></view>
          </view>
        </view>
        <view class="filter-dialog" :class="{'active': showFilterDialog}">
          <view class="tag-groups" v-if="dialogType === dialogEunm.TAG_GROUPS">
            <view 
              class="filter-item" 
              v-for="(item, index) in groupTags" 
              :key="index" 
              :class="{'active': groupTagCur?.id === item.id}"
              @click="handleTagGroup(item, index)"
            >{{item.tagName}}</view>
          </view>
          <view class="tag-groups" v-if=" dialogType === dialogEunm.TAG_ITEMS">
            <view class="filter-item" 
              v-for="(item, index) in groupTagChilds" 
              :key="index" 
              :class="{'active': groupTagChildCur?.id === item.id}"
              @click="handleTagItem(item, index)"
            >{{item.tagName}}</view>
          </view>
          <view class="tag-groups" v-if=" dialogType === dialogEunm.SORT">
            <view 
              class="filter-item" 
              v-for="(item, index) in sortTypes" 
              :key="index"  
              :class="{'active': queryData.sortType === item.value}"
              @click="handleSortItem(item, index)"
            >{{item.title}}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="mask" v-if="showFilterDialog" @click="closeFilterDialog"></view>
    <view class="products">
      <view class="tit">产品列表</view>
      <view class="products-content">
        <template v-for="(item, index) in productList" :key="index">
          <Product :product="item" />
        </template>
      </view>
      <view v-if="queryStatus.productEmpty" class="empty">未匹配到产品，请更换条件</view>
    </view>
    </view>
    <TabBar :type="2"></TabBar>
    <Login />
  </view>
</template>

<script setup>
import { reactive, ref, computed, watch } from 'vue'
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import Notices from '../../components/notices/index.vue' ;
import Product from '@/components/product/Product.vue' ;
import nva_new_product from '@/static/svg/nva_new_product.svg'
import nva_order from '@/static/svg/nva_order.svg'
import nva_hot from '@/static/svg/nva_hot.svg'
import nva_point from '@/static/svg/nva_point.svg'

import { useStore } from 'vuex'
import { getProductList, getTagListAllApi } from '@/api/product'
import { getTagGroup } from '@/utils/product'

const store = useStore()
const isLogin = computed(()=> {
  return store.state.user.isLogin
})
watch(
  () => isLogin.value,
  (v) => {
    v && init()
  },
);
const userPointCount = computed(()=> {
  return store.state.user.userPointCount
})
// import 
const groupTags = ref([])
const tagsAll = ref([])
const dialogEunm = ref({
  'TAG_GROUPS': 'TAG_GROUPS',
  'TAG_ITEMS': 'TAG_ITEMS',
  'SORT': 'SORT',
})
const dialogType = ref('')

const sortTypes = ref([
  {
    title: '综合排序',
    value: 1,
  },
  {
    title: '积分从高到低',
    value: 2,
  },{
    title: '积分从低到高',
    value: 3,
  },
])

const getSortTitle = computed(()=> {
  if(queryData.sortType) {
    const sortType = sortTypes.value.find((item)=> item.value === queryData.sortType)
    return sortType?.title || '筛选'
  }
  return '筛选'
})
const queryData = reactive({
  page: 1,
  size: 10,
  productType: 2,
  sortType: '',
  tagIds: '',
  keyword: '',
})

const queryStatus = reactive({
  isLoaded: false,
  loading: false,
  productEmpty: false
})



const productList = ref([])

const showFilterDialog = ref(false)

const queryTag = computed(()=> {
  const id = queryData.tagIds;
  const matched = tagsAll.value.find(item => item.id == id)
  if(matched) {
    return matched
  }
  return null
});

const groupTagCur = computed(()=> {
  const { id, parentId }  = queryTag.value || {}
  if(parentId) {
    return groupTags.value.find(item => item.id == parentId)
  } else if(id) {
    return groupTags.value.find(item => item.id == id)
  }
  return null
})

const groupTagChilds = computed(()=> {
  const groups = groupTagCur.value
  if(groups?.subGroups) {
    return groups?.subGroups
  } 
  return []
})
const groupTagChildCur = computed(()=> {
  const id = queryData.tagIds;
  if(groupTagCur.value && id) {
    const groups = groupTagCur.value
    return groups.subGroups.find(item => item.id == id)
  }
  return null
})

const groupTagChildTitle = computed(()=> {
  // console.log('groupTagChildCur', groupTagChildCur)
  return groupTagChildCur.value?.tagName || `全部${groupTagCur.value?.tagName || ''}`
})

onLoad(async ()=> {
  await getTagListAll()
  init()
})

onPullDownRefresh( async ()=> {
  await init().finally(() => {
    uni.stopPullDownRefresh();
  });
})
onReachBottom(()=> {
  if(queryStatus.isLoaded){
    return
  }
  queryData.page += 1;
  getProduct()
})
async function init() {
  store.dispatch('user/getUserPointCount')
  queryData.tagIds = ''
  await productReload()
}
async function productReload(){
  queryData.page = 1;
  queryStatus.isLoaded = false

  await getProduct()
}
async function getTagListAll(){
  // debugger
  const res = await getTagListAllApi({type: 2})
  tagsAll.value = res
  groupTags.value =  getTagGroup(res)
  // console.log('groupTags', groupTags)
}

async function getProduct(){
  if(queryData.isLoaded) {
    return 
  }
  queryStatus.loading = true
  queryStatus.productEmpty = false
  uni.showLoading()
  const res = await getProductList({
    ...queryData
  }).finally(()=> {
    queryStatus.loading = false
    uni.hideLoading()
  })
  if(queryData.page === 1) {
    productList.value = [...res.items] 
  } else {
    productList.value.push(...res.items)
  }
  if(!productList.value.length) {
      queryStatus.productEmpty = true
  }
  if(productList.value.length === res.total) {
    queryStatus.isLoaded = true
  } else {
    queryStatus.isLoaded = false
  }
}

function handleOpenFilter(type){
  if(dialogType.value === type && showFilterDialog.value ){
    showFilterDialog.value = false
  } else {
    dialogType.value = type
    showFilterDialog.value = true
  }
}

function closeFilterDialog() {
  showFilterDialog.value = false
}

function handleTagGroup(data, index){
  if(queryData.tagIds === data.id) {
      queryData.tagIds = ''
  } else {
     queryData.tagIds = data.id
  }
  closeFilterDialog()
  productReload()
}

function handleTagItem(data, index){
  const { id, parentId }  = data
  if(queryData.tagIds === id) {
      queryData.tagIds = parentId
  } else {
     queryData.tagIds = id
  }
  closeFilterDialog()
  productReload()
}


function handleSortItem(data, index) {
  if(queryData.sortType ===  data.value){
  queryData.sortType = ''
  } else {
  queryData.sortType = data.value
  }
 
  closeFilterDialog()
  productReload()
}

function handleToDetail(){
  uni.navigateTo({
    url: '/subpkgs/mine/point/detail'
  })
}

</script>

<style lang='scss' scoped>
.main{
  min-height: 100vh;
  background: #F4F6F8;
  .top{
    // height: 234rpx;
    background: url(https://oss.cqxzx.com/77d0e39504df7d53322141ec9f3fc8fe.png?Expires=2036752558&OSSAccessKeyId=LTAI5t5a98jUcHvqdxwzahgm&Signature=gTvCvAbADG2TTs%2BusWJplMYcYok%3D) center bottom no-repeat;
    background-size: cover;
    position: relative;
    z-index: 10;
    .point-box{
      height: 234rpx;
      padding: 56rpx 32rpx 0 32rpx;
    }
    .point-total{
      font-weight: 700;
      font-size: 98rpx;
      color: #FFFFFF;
      line-height: 1;
      margin-bottom: 16rpx;
    }
    .point-btns{
      display: flex;
      font-weight: 400;
      font-size: 26rpx;
      color: #FFFFFF;
      line-height: 34rpx;
      gap: 14rpx;
      align-items: baseline;
    }
  }
  .header{
    position: relative;
    z-index: 5;
  }
  .search{
    position: relative;
    z-index: 10;
    height: 112rpx;
    background: #FFFFFF;
    border: 1rpx solid #EEEEEE;
    padding: 18rpx 32rpx;
    .search-box{
      height: 100%;
      background: #F2F2F2;
      border-radius: 55rpx;
      position: relative;
      .search-icon{
        position: absolute;
        z-index: 1;
        top: 50%;
        transform: translateY(-50%);
        width: 28rpx;
        height: 28rpx;
        left: 32rpx;
      }
      .search-input{
        display: flex;
        height: 100%;
        padding-left: 76rpx;
        align-items: center;
        font-weight: 400;
        font-size: 26rpx;
        color: #999999;
        line-height: 34rpx;
      }
    }

  }
  .filter{
    position: relative;
    .filter-box{
      height: 80rpx;
      background: #fff;
      display: flex;
      align-items: center;
      position: relative;
      z-index: 10;
      justify-content: space-between;
      .filter-type-item{
        font-weight: 400;
        font-size: 26rpx;
        display: flex;
        padding: 0 32rpx;
        line-height: 36rpx;
        justify-content: space-between;
        position: relative;
        width: 0;
        max-width: 40vw;
        &.active{
          color: #FF8F1F;
        }
        .filter-name{
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .iconfont{
          transition: all .3s;
        }
        &.open{
          .iconfont{
            transform: rotate(180deg);
          }
        }
        &:after{
          position: absolute;
          top: 50%;
          right: 0;
          content: '';
          display: block;
          height: 32rpx;
          width: 1px;
          background: #EEEEEE;
          transform: translateY(-50%);
        }
  
      }
      .filter-classify{
        flex: 1;
        line-height: 36rpx;
        padding-left: 35rpx;
      }
      .filter-sort{
        width: auto;
      }
    }
    .filter-dialog{
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      background: #fff;
      z-index: -1;
      transform: translateY(-80vh);
      transition: all .3s;
      &.active{
        transform: translateY(0);
      }
      .tag-groups{
        max-height: 50vh;
        overflow: auto;
        .filter-item{
          display: flex;
          align-items: center;
          padding: 0 32rpx;
          height: 98rpx;
          font-weight: 400;
          font-size: 26rpx;
          color: #333;
          line-height: 36rpx;
          &.active{
            color: #FF8F1F;
          }
        }
      }
    }
  }
  .mask{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    background: rgba(0,0,0, 0.4);
  }
  .products{
    background: #fff;
    padding: 32rpx;
    margin-top: 20rpx;
    .tit{
      font-weight: 500;
      font-size: 28rpx;
      color: #333333;
      line-height: 36rpx;
      margin-bottom: 20rpx;
    }
    .products-content{
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24rpx;
    }
    .empty{
      text-align: center;
      line-height: 40vh;
      font-size: 28rpx;
      color: #333333;
    }
  }
}
</style>
